package android.medicalcloud.com.yiapp.yilian.ui.ac;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.medicalcloud.com.yiapp.R;
import android.medicalcloud.com.yiapp.base.activity.BaseActivity;
import android.medicalcloud.com.yiapp.yilian.ui.view.clipimage.ClipImageLayout;
import android.medicalcloud.com.yiapp.yilian.ui.view.clipimage.WeakReferenceHandler;
import android.medicalcloud.com.yiapp.yilian.utils.android.IntentTool;
import android.medicalcloud.com.yiapp.yilian.utils.android.ToastTool;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;


import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;



/**
 * 图片裁剪的页面
 * Created by HW on 2015/8/27.
 */
public class CropImageActivity extends BaseActivity implements View.OnClickListener {

    private static final int LOAD_BITMAP_BEGIN = 1;
    private static final int LOAD_BITMAP_SUCCESS = 2;
    private static final int CROP_IMAGE_BEGIN = 3;
    private static final int CROP_IMAGE_SUCCESS = 4;
    private static final int CROP_IMAGE_FAIL = 5;

    public static final String IMAGE_PATH = "image-path";
    public static final String IMAGE_CROP_PATH = "image-crop-path";
    public static final String OUTPUT_X = "outputX";
    public static final String OUTPUT_Y = "outputY";
    public static final String RETURN_DATA = "return-data";
    public static final String RETURN_DATA_AS_BITMAP = "data";
    public static final String ACTION_INLINE_DATA = "inline-data";

    public static final int DEFAULT_OUTPUT_X = 300;
    public static final int DEFAULT_OUTPUT_Y = 300;

    ClipImageLayout clipImageLayout;
    TextView btnCancel;
    TextView btnSave;

    private int mOutputX = DEFAULT_OUTPUT_X;
    private int mOutputY = DEFAULT_OUTPUT_Y;
    private Bitmap.CompressFormat mOutputFormat = Bitmap.CompressFormat.JPEG;
    private Uri mSaveUri = null;
    private String mImagePath;
    private Bitmap mBitmap = null;
    private boolean isReturnData = false;


    @Override
    protected void initView() {
        clipImageLayout =(ClipImageLayout) findViewById(R.id.crop_image_view);
        btnCancel =(TextView) findViewById(R.id.crop_btn_cancel);
        btnSave =(TextView) findViewById(R.id.crop_btn_save);
    }

    @Override
    protected void initEvent() {
        btnSave.setOnClickListener(this);
        btnCancel.setOnClickListener(this);
    }



    @Override
    protected int getLayoutId() {
        return R.layout.ac_crop_image;
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (null == extras) {

            return;
        }
        mOutputX = extras.getInt(OUTPUT_X, DEFAULT_OUTPUT_X);
        mOutputY = extras.getInt(OUTPUT_Y, DEFAULT_OUTPUT_Y);
        mImagePath = extras.getString(IMAGE_PATH);
        isReturnData = extras.getBoolean(RETURN_DATA);
        mSaveUri = getSaveImageUri();
        loadBitmap();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.crop_btn_save:
                if (isReturnData) {
                    returnData();
                } else {
                    new Thread(saveBitmapRunnable).start();
                }
                break;
            case R.id.crop_btn_cancel:
                cancel();
                break;
        }
    }

    private void loadBitmap() {
        if (TextUtils.isEmpty(mImagePath)) {
            return;
        }
//        CommonLoadingUtils.showLoadingMessage(CropImageActivity.this,"",true);
        new Thread(loadBitmapRunnable).start();
    }

    private WeakReferenceHandler<CropImageActivity> mWeakHandler = new WeakReferenceHandler<CropImageActivity>(CropImageActivity.this) {
        @Override
        protected void handleMessage(CropImageActivity reference, Message msg) {
            switch (msg.what) {
                case LOAD_BITMAP_BEGIN:

                    break;
                case LOAD_BITMAP_SUCCESS:
                    /*Drawable d = new BitmapDrawable(getResources(), mBitmap);
                    cropImageView.setDrawable(d,mOutputX,mOutputY);*/
                    if (null != mBitmap) {
                        clipImageLayout.setBitmap(mBitmap);
                    } else {
                        //ToastTool.show(R.string.crop_image_load_error);
                    }

                    break;
                case CROP_IMAGE_BEGIN:
                    break;
                case CROP_IMAGE_FAIL:
                    //ToastTool.show(R.string.crop_image_save_fail);

                    break;
                case CROP_IMAGE_SUCCESS:

                    returnData();
                    break;
            }
        }
    };

    /****
     * 返回数据
     */
    private void returnData() {
        /*Bundle myExtras = getIntent().getExtras();
        if (myExtras != null && (myExtras.getParcelable("data") != null
                || myExtras.getBoolean(RETURN_DATA))) {*/
        if (isReturnData) {
            Bundle extras = new Bundle();
//            extras.putParcelable(RETURN_DATA_AS_BITMAP, cropImageView.getCropImage());
            extras.putParcelable(RETURN_DATA_AS_BITMAP, clipImageLayout.clip());
            setResult(RESULT_OK,
                    (new Intent()).setAction(ACTION_INLINE_DATA).putExtras(extras));
            finish();
        } else {
//            Bundle extras = new Bundle();
//            Intent intent = new Intent(mSaveUri.toString());
//            intent.putExtras(extras);
//            intent.putExtra(IMAGE_PATH, mSaveUri.getPath());
//            setResult(RESULT_OK, intent);
            IntentTool.startSubmitAvatar(this, mSaveUri.getPath());
            finish();
        }
    }

    /****
     * 加载并显示图片
     */
    Runnable loadBitmapRunnable = new Runnable() {
        @Override
        public void run() {
            mWeakHandler.sendEmptyMessage(LOAD_BITMAP_BEGIN);
            int mHorizontalPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 60, getResources().getDisplayMetrics());
            WindowManager windowManager = getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            int width = display.getWidth() - 2 * mHorizontalPadding;
//            mBitmap = ImageUtils.decodeBitmapFromSDCard(mImagePath, CommonUtils.getScreenWidth(), CommonUtils.getScreenHeight());
            mBitmap = decodeBitmapFromSDCard(mImagePath, width, width);
            mWeakHandler.sendEmptyMessage(LOAD_BITMAP_SUCCESS);
        }
    };

    private Bitmap decodeBitmapFromSDCard(String path,
                                          int reqWidth, int reqHeight) {

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPreferQualityOverSpeed = true;//增加图片显示质量
        try {
            return BitmapFactory.decodeFile(path, options);
        } catch (Exception e) {
        }
        return null;
    }

    private int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {

        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (height > reqHeight && reqHeight != 0) {
                inSampleSize = (int) Math.floor((double) height / (double) reqHeight);
            }

            int tmp = 0;

            if (width > reqWidth && reqWidth != 0) {
                tmp = (int) Math.floor((double) width / (double) reqWidth);
            }

            inSampleSize = Math.max(inSampleSize, tmp);

        }
        int roundedSize;
        if (inSampleSize <= 8) {
            roundedSize = 1;
            while (roundedSize < inSampleSize) {
                roundedSize <<= 1;
            }
        } else {
            roundedSize = (inSampleSize + 7) / 8 * 8;
        }

        return roundedSize;
    }

    Runnable saveBitmapRunnable = new Runnable() {
        @Override
        public void run() {
            mWeakHandler.sendEmptyMessage(CROP_IMAGE_BEGIN);
            Bitmap bitmap = null;
            if (mSaveUri != null) {
                OutputStream outputStream = null;
                try {
                    outputStream = getContentResolver().openOutputStream(mSaveUri);
                    if (outputStream != null) {
                        bitmap = clipImageLayout.clip();
                        bitmap.compress(mOutputFormat, 100, outputStream);
                    }
                    mWeakHandler.sendEmptyMessage(CROP_IMAGE_SUCCESS);
                } catch (IOException ex) {
                    /*LogUtils.e("Cannot open file: " + mSaveUri, ex);
                    setResult(RESULT_CANCELED);
                    finish();
                    return;*/
                    ex.printStackTrace();
                    mWeakHandler.sendEmptyMessage(CROP_IMAGE_FAIL);
                } finally {
                    if (outputStream == null) return;
                    try {
                        outputStream.close();
                        if (null != bitmap) {
                            bitmap.recycle();
                            bitmap = null;
                        }
                    } catch (Throwable t) {
                    }
                }
                /*Message msg = mWeakHandler.obtainMessage(CROP_IMAGE_SUCCESS);
                Bundle bundle = new Bundle();
                bundle.putString("data",);
                msg.setData();*/
            } else {
                mWeakHandler.sendEmptyMessage(CROP_IMAGE_FAIL);
            }
        }
    };

    private Uri getSaveImageUri() {
        return Uri.fromFile(createTmpFile(getApplicationContext()));
    }

    private File createTmpFile(Context context) {

        String state = Environment.getExternalStorageState();

        File cacheDir = context.getCacheDir();
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
        String fileName = "multi_image_" + timeStamp + "";
        File tmpFile = new File(cacheDir, fileName + ".jpg");
        return tmpFile;


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            cancel();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    /****
     * 取消
     */
    private void cancel() {

        finish();
    }


}
